<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Log;

class AuthToken extends BaseMiddleware
{
    /**
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        Log::info('auth token.');
        Log::info(json_encode($request->header('Authorization')));
        Log::info(json_encode(\Auth::guard('member')->user()));
        try {
            if (!$user =  \Auth::guard('member')->user()) {  //获取到用户数据，并赋值给$user
                return response()->json([
                    'code' => 200200,
                    'msg' => trans(config('error.200200')),
                    'data'=> null

                ]);
            }
            return $next($request);

        } catch (TokenExpiredException $e) {

            return response()->json([
                'code' => 100003,
                'msg' => trans(config('error.100003')) , //token已过期
                'data'=> null
            ]);

        } catch (TokenInvalidException $e) {

            return response()->json([
                'code' => 100002,
                'msg' => trans(config('error.100002')),  //token无效
                'data'=> null
            ]);

        } catch (JWTException $e) {

            return response()->json([
                'code' => 100001,
                'msg' => trans(config('error.100001')) , //token为空
                'data'=> null
            ]);

        }

    }
}